package com.ricohgag.controller.home;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ricohgag.entity.RechargeLog;
import com.ricohgag.entity.ShopOrder;
import com.ricohgag.entity.UserAddress;
import com.ricohgag.entity.VipUser;
import com.ricohgag.entity.custom.ShopOrderGoodsVo;
import com.ricohgag.service.*;
import com.ricohgag.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author ricohgag
 * @date 2018/9/5 16:23
 */
@Controller
@RequestMapping("/home/center")
public class HomeCenterController {
    @Autowired
    private VipUserService vipUserService;
    @Autowired
    private RechargeLogService rechargeLogService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private ShopOrderGoodsService shopOrderGoodsService;

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) throws Exception{
        VipUser vipUserSession = (VipUser)request.getSession().getAttribute("vipUserSession");
        ModelAndView mav = new ModelAndView("/home/center/index");
        if(vipUserSession == null){
            mav.setViewName("redirect:/home/index/index");
            return mav;
        }

        //1.控制底色 2、3.查询完成/未完成订单数量
        mav.addObject("navActive", 3);
        int countConfrim = shopOrderService.count(new QueryWrapper<ShopOrder>().eq("shop_state", 3).eq("user_id", vipUserSession.getId()));
        int notConfrim = shopOrderService.count(new QueryWrapper<ShopOrder>().eq("shop_state", 1).eq("user_id", vipUserSession.getId()));
        VipUser vipUser = vipUserService.selectVipUserOne(vipUserSession.getId());


        mav.addObject("countConfrim", countConfrim);
        mav.addObject("notConfrim", notConfrim);
        mav.addObject("vipUser", vipUser);


        return mav;
    }

    @RequestMapping("/proinfo")
    public ModelAndView proinfo(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/home/center/proinfo");

        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        mav.addObject("vipUser", vipUser);
        return mav;
    }

    @RequestMapping("/submitProinfo")
    @ResponseBody
    public Msg submitProinfo(HttpServletRequest request, String phone, String email, String userImg) throws Exception{
        Msg msg = new Msg();

        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        vipUser.setPhone(phone);
        vipUser.setEmail(email);
        vipUser.setUserImg(userImg);

        int count = vipUserService.updateVipUser(vipUser);
        if(count>0){
            msg.setStatus(1);
            msg.setMsg("操作成功");
        } else {
            msg.setStatus(0);
            msg.setMsg("操作失败");
        }

        return msg;
    }

    /**
     * 进入更改密码页面
     * @return
     */
    @RequestMapping("/password")
    public String password() {
        return "/home/center/password";
    }

    /**
     * ajax更改会员信息
     * @param request
     * @param oldPassword
     * @param newPassword
     * @param newPassword1
     * @return
     * @throws Exception
     */
    @RequestMapping("/submitPassword")
    @ResponseBody
    public Msg submitPassword(HttpServletRequest request, String oldPassword, String newPassword, String newPassword1)throws Exception{
        Msg msg = new Msg();
        VipUser onlineUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        if(newPassword.equals(newPassword1)){
            if(onlineUser.getPassword().equals(oldPassword)){
                onlineUser.setPassword(newPassword);
                vipUserService.updateVipUser(onlineUser);
                msg.setStatus(1);
                msg.setMsg("密码修改成功，请重新登录");
                request.getSession().removeAttribute("vipUserSession");
            }
        } else {
            msg.setStatus(0);
            msg.setMsg("密码修改失败。");
        }

        return msg;
    }

    /**
     * 退出会员登录
     * @param request
     * @return
     */
    @RequestMapping("/userExit")
    public String userExit(HttpServletRequest request)throws Exception{
        request.getSession().removeAttribute("vipUserSession");
        return "redirect:/home/index/login";
    }


    /******************余额管理************************/
    @RequestMapping("/recharge")
    public String recharge(Model model, HttpServletRequest request)throws Exception{
        return "/home/center/recharge";
    }

    /**
     * ajax提交充值
     * @return
     */
    @RequestMapping("/submitRecharge")
    @ResponseBody
    public Msg submitRecharge(HttpServletRequest request, BigDecimal orderAmount) throws Exception{
        Msg msg = new Msg();
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        vipUser.setRechargeMoney(vipUser.getRechargeMoney().add(orderAmount));

        int count = vipUserService.updateVipUser(vipUser);
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");

        RechargeLog rechargeLog = new RechargeLog();
        rechargeLog.setAddTime(LocalDateTime.now());
        rechargeLog.setMoney(orderAmount);
        rechargeLog.setUserId(vipUser.getId());
        String snId = sdf.format(new Date());
        rechargeLog.setRechargeSn(snId);
        rechargeLogService.insertRechargeLogs(rechargeLog);

        if(count>0){
            msg.setStatus(1);
            msg.setMsg("充值成功");
        } else {
            msg.setStatus(0);
            msg.setMsg("充值失败");
        }
        System.out.println("msg: "+msg);
        return msg;
    }

    /**
     * 充值记录页面
     * @return
     * @throws Exception
     */
    @RequestMapping("/rechargeIndex")
    public ModelAndView rechargeIndex(HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView("/home/center/rechargeIndex");
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");

        List<RechargeLog> rechargeLogs = rechargeLogService.selectRechargeLogs(vipUser.getId());
        mav.addObject("rechargeLogs", rechargeLogs);

        return mav;
    }


    /*****************订单管理***********************/
    @RequestMapping("/orderIndex")
    public ModelAndView orderIndex(HttpServletRequest request, ModelMap modelMap, Integer current) throws Exception{
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        ModelAndView mav = new ModelAndView("home/center/orderIndex");
        if(current == null){
            current = 1;
        }
        Page<ShopOrder> page = new Page<>(current, 10);

        IPage<ShopOrder> orderIPage = shopOrderService.selectOrderByUserId(vipUser.getId(), page);
        System.err.println("orderIPage: "+orderIPage.getRecords().size());
        mav.addObject("orderIPage", orderIPage);

        return mav;
    }


    /**
     * 前台订单详情
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/orderDetail")
    public ModelAndView orderDetail(HttpServletRequest request, Integer id) throws Exception{
        ModelAndView mav = new ModelAndView("home/center/orderDetail");
        ShopOrder shopOrder = shopOrderService.selectOrderById(id);
        List<ShopOrderGoodsVo> orderGoodsList = shopOrderGoodsService.selectGoodsByOrderId(id);
        mav.addObject("shopOrder", shopOrder);
        mav.addObject("orderGoodsList", orderGoodsList);

        return mav;
    }

    /**
     * 确认收货
     * @return
     */
    @RequestMapping("/affirm")
    public String affirm(Integer id){
        //更改订单状态为完成
        shopOrderService.updateStatusById(id, 3);
        return "redirect:/home/center/orderDetail?id="+id;
    }


    @RequestMapping("/addressIndex")
    public String addressIndex(HttpServletRequest request, ModelMap modelMap) throws Exception{
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        List<UserAddress> addressList = userAddressService.selectAddressByUserId(vipUser.getId());
        modelMap.put("addressList", addressList);

        return "home/center/addressIndex";
    }

    @RequestMapping("/editorAddress")
    public String editorAddress(Integer id, ModelMap modelMap) throws Exception{
        if(id != null){
            UserAddress address = userAddressService.selectOneById(id);
            modelMap.put("address", address);
        }

        return "home/center/editorAddress";
    }

    @RequestMapping("/submitEditorAddress")
    public String submitAddEditorAddress(HttpServletRequest request, UserAddress userAddress) throws Exception{
        VipUser vipUser = (VipUser)request.getSession().getAttribute("vipUserSession");
        if(userAddress.getId() == null){
            userAddress.setUserId(vipUser.getId());
            userAddressService.insert(userAddress);
        } else {
            userAddressService.update(userAddress);
        }

        return "redirect:/home/center/addressIndex";
    }

    @RequestMapping("/deleteAddress")
    @ResponseBody
    public Msg deleteAddress(Integer id) throws Exception{
        Msg msg = new Msg();
        boolean flag = userAddressService.delete(id);
        if(flag){
            msg.setStatus(1);
        } else {
            msg.setStatus(0);
        }

        return msg;
    }

}
